<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showDialog">添 加</el-button>
      </div>
    </template>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="trademarkList" border style="width: 100%;margin-bottom:20px">
      <el-table-column type="index" align="center" label="序号" width="90" />
      <el-table-column prop="tmName" label="品牌名称" width="180" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{row}">
          <img :src="row.logoUrl" width="100" alt="">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{row}"> 
          <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
            <el-button type="warning" size="small" :icon="Edit" @click="toEditTrademark(row)"></el-button>
          </el-tooltip>

          <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
            <el-button type="danger" size="small" :icon="Delete" @click="delTrademark(row.id)"></el-button>
          </el-tooltip>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3,5,10,20]" :small="small" :disabled="disabled" :background="background" layout="prev, pager, next, jumper,->,sizes,total" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 添加或更改品牌时的弹出框 -->
    <el-dialog v-model="dialogFormVisible" :title="`${trademarkInfo.id?'修改':'添加'}品牌`">
      <el-form ref="trademarkRef" :model="trademarkInfo" :rules="trademarkRules">
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input v-model="trademarkInfo.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/fileUpload`" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png 文件大小不能超过2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="btnTrademark(trademarkRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'Trademark'
});
</script>

<script setup lang="ts">
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { ref, onMounted, reactive } from 'vue';
import type { UploadProps } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { reqDeleteTrademarkInfo, reqGetTrademarkList, reqSaveTrademarkInfo, reqUpdateTrademarkInfo } from '@/api/product/trademark';
import type { TrademarkListModel, TrademarkModel } from '@/api/product/interface/trademarkModel';
const currentPage = ref<number>(1);
const pageSize = ref<number>(3);
const small = ref<boolean>(false);
const background = ref<boolean>(false);
const disabled = ref<boolean>(false);
const trademarkList = ref<TrademarkListModel>([]);
const total = ref<number>(0);
const loading = ref<boolean>(false);
const imageUrl = ref('');
const trademarkRef = ref<FormInstance>();
const dialogFormVisible = ref(false);
const formLabelWidth = '100px';
// console.log('aa',import.meta.env.VITE_API_URL)
const baseUrl = import.meta.env.VITE_API_URL;

// const initTrademark = ()=>{
//   return {
//     tmName:'',
//     logoUrl:''
//   }
// }

const initTrademark = () => ({
  tmName: '',
  logoUrl: ''
});
// info后缀一般表示对象 list后缀一般表示数组
// const trademarkInfo = reactive<TrademarkModel>({
//   tmName: '',
//   logoUrl: ''
// });
const trademarkInfo = reactive<TrademarkModel>(initTrademark());

const trademarkRules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 1, max: 6, message: '品牌名称应该是在1到6之间', trigger: 'blur' }
  ],
  logoUrl: [
    {
      required: true,
      message: '请上传一张图片',
      trigger: 'change'
    }
  ]
});
// 1. 封装获取品牌列表的函数
const getTrademarkList = async () => {
  loading.value = true; // 显示loading效果
  const result = await reqGetTrademarkList(currentPage.value, pageSize.value);
  // console.log('rr',result)
  trademarkList.value = result.records;
  total.value = result.total;
  loading.value = false; // 关闭loading效果
};
// 2. 页面加载完成就发送请求
onMounted(() => {
  getTrademarkList();
});

// 3. 当页面改变的时候
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`);
  currentPage.value = val;
  getTrademarkList(); // 根据当前新的页面，重新发送请求
};

// 4. 当当前页码显示的数量变化时
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  getTrademarkList();
};

// 5. 图片上传之前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  // console.log('rr', rawFile);
  const imgArr = ['image/jpeg', 'image/png'];
  // if (rawFile.type !== 'image/jpeg') {
  if (!imgArr.includes(rawFile.type)) {
    ElMessage.error('图片格式必须是"image/jpeg或image/png"!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M!');
    return false;
  }
  return true;
};

// 6. 图片上传成功之后的链接地址
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // response是服务器端响应回来的数据 uploadFile包含的更多 包含原文件和服务器返回的数据
  // console.log('uu',response,uploadFile)
  // !用在数据的最后 表示非空断言
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  trademarkInfo.logoUrl = response.data;

  // 清除校验规则
  trademarkRef.value?.clearValidate(['logoUrl']);
};

// 7. 添加trademark或更新trademark
// const saveTrademark = async () => {
// const submitForm = async (formEl: FormInstance | undefined) => {
//   if (!formEl) return
//   await formEl.validate((valid, fields) => {
//     if (valid) {
//       console.log('submit!')
//     } else {
//       console.log('error submit!', fields)
//     }
//   })
// }
// const btnTrademark = async () => {
const btnTrademark = async (formEl: FormInstance | undefined) => {
  if (!formEl) return; // 如果没有值 则不再往下执行
  await formEl.validate(async (valid, fields) => {
    // console.log('vv', valid, fields);
    if (valid) {
      // 校验通过后，再执行以下业务
      if (trademarkInfo.id) {
        // 如果有id值 此时说明是更新品牌
        await reqUpdateTrademarkInfo(trademarkInfo);
      } else {
        // 没有id值 此时说明是添加操作
        await reqSaveTrademarkInfo(trademarkInfo);
      }

      ElMessage.success(`${trademarkInfo.id ? '更新' : '添加'}品牌成功了...`);
      // ElMessage({
      //   type:'success',
      //   message:'添加品牌成功了...'
      // })
      // 重新发送请求 根据当前页码获取最新的数据
      getTrademarkList();
      dialogFormVisible.value = false;
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 8. 单击添加按钮 显示对话框
const showDialog = () => {
  // trademarkInfo.tmName = '';
  // trademarkInfo.logoUrl = '';

  // 清除校验规则  没有参数的时候，表示清除所有的校验规则
  trademarkRef.value?.clearValidate();

  delete trademarkInfo.id; // 删除id
  // 清空原对象中的属性值
  Object.assign(trademarkInfo, initTrademark());
  imageUrl.value = '';
  dialogFormVisible.value = true;
};

// 9. 删除trademark
const delTrademark = (id: number) => {
  ElMessageBox.confirm('您真的要删除此商品品牌吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await reqDeleteTrademarkInfo(id);
      ElMessage({
        type: 'success',
        message: '删除成功'
      });

      // 还是要重新发送请求 获取数据
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      });
    });
};

// 10. 更新品牌之数据回显
const toEditTrademark = (row: TrademarkModel) => {
  // 10.1 接收待更改的数据
  // 10.2 要弹出对话框 显示相应的数据

  // 1. 先赋值给trademarkInfo
  Object.assign(trademarkInfo, row);
  imageUrl.value = row.logoUrl;
  // 2. 弹出对话框时 显示要更新的数据
  dialogFormVisible.value = true;

  // 清除校验规则  没有参数的时候，表示清除所有的校验规则
  trademarkRef.value?.clearValidate();
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>